//=============================================================================
#include "CApp.h"

//=============================================================================
void CApp::OnEvent(SDL_Event* Event) {
    CEvent::OnEvent(Event);
}

//-----------------------------------------------------------------------------
void CApp::OnUser(Uint8 type, int code, void* data1, void* data2) {
    //data1 = Socket

    switch(code) {
        case NET2_TCPACCEPTEVENT: {
            int Socket = (int)data1;

            CClients* Client = CClients::FindAvailable();

            if(Client == NULL) {
                CLog::Notice("No Slots Available - Denied");
            }else{
                Client->Connect(Socket);

                CLog::Notice("New Client Connected");
            }

            break;
        }

        case NET2_TCPRECEIVEEVENT: {
            int Socket      = (int)data1;
            int DataLength  = 0;

            CClients* Client = CClients::FindBySocket((int)data1);

            if(Client) {
                CNetworkPacket* Packet = Client->GetReadPacket();

                int Return = 0;

                do {
                    if(Packet->NeedsHeader())   Return = Packet->ReadHeader(Client->GetSocket());
                    else                        Return = Packet->ReadData(Client->GetSocket());

                    if(Packet->IsReady())       Packet = Client->GetReadPacket();
                }while(Return > 0);
            }

            break;
        }

        case NET2_TCPCLOSEEVENT: {
            CClients* Client = CClients::FindBySocket((int)data1);

            if(Client) {
                CLog::Notice("Client Disconnected / Lost");

                if(Client->PlayerID > 0) {
                    CLua::LuaControl.PushFunction("OnEvent");
                    CLua::LuaControl.PushArgNumber(EVENT_PLAYER_LOGGED_OUT);
                    CLua::LuaControl.PushArgNumber(Client->PlayerID);
                    CLua::LuaControl.PushArgNumber(0);
                    CLua::LuaControl.Call();
                }

                Client->Disconnect();
            }

            break;
        }

        case NET2_ERROREVENT: {
            //printf("Error: %s\n", NET2_GetEventError(&ev));
            break;
        }
    }
}

//=============================================================================
